package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.itheima.dao.PermissionDao;
import com.itheima.domain.Permission;
import com.itheima.factory.MapperFactory;
import com.itheima.service.PermissionService;
import com.itheima.utils.TransactionUtil;
import com.itheima.utils.xiaohu_utils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class PermissionServiceImpl implements PermissionService {

    //分页查询页面所有
    @Override
    public List<Permission> findAll(String pageNum, String pageSize) {
        SqlSession sqlSession= null;
        try {
            sqlSession= MapperFactory.getSqlSession();
            PermissionDao permissionDao = MapperFactory.getMapper(sqlSession, PermissionDao.class);
            int i=1;
            int j=5;
            if (StringUtil.isNotEmpty(pageNum)){
                i=Integer.parseInt(pageNum);
            }
            if (StringUtil.isNotEmpty(pageSize)){
                j=Integer.parseInt(pageSize);
            }
            PageHelper.startPage(i,j);
            List<Permission> companies = permissionDao.findAll();
            TransactionUtil.commit(sqlSession);
            return companies;
        }catch (Exception e){
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
        }

        return null;
    }

    @Override
    public void save(Permission permission) {
        SqlSession sqlSession= null;
        try {
            sqlSession= MapperFactory.getSqlSession();
            PermissionDao permissionDao = MapperFactory.getMapper(sqlSession, PermissionDao.class);
            String id = xiaohu_utils.getUUID22();
            permission.setId(id);
            permissionDao.save(permission);
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
        }
    }

    @Override
    public void deleteById(String id) {
        SqlSession sqlSession= null;
        try {
            sqlSession= MapperFactory.getSqlSession();
            PermissionDao permissionDao = MapperFactory.getMapper(sqlSession, PermissionDao.class);
            String[] ids = id.split(",");
            for (int i = 0; i < ids.length; i++) {
                //permissionDao.deleteRP(ids[i]);//删除关联
                permissionDao.deleteById(ids[i]);
            }

            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
        }
    }
}
